package com.geekhome.gateways.controller;

import com.geekhome.global.common.JsonResult;
import com.geekhome.global.common.ZnxzExceptioon;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Copyright © 2019年 zn-security. All rights reserved.
 *
 * @author 临江仙 hzqiuxm@163.com
 * 接口层全局异常类
 * @date 2019/8/24 15:19
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {


    @ExceptionHandler(ZnxzExceptioon.class)
    public JsonResult handingException(ZnxzExceptioon ex) {

        return new JsonResult(ex.getCode(), ex.getMessage(), null);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult<?> validationErrorHandler(MethodArgumentNotValidException ex) {

        List<String> errorInformation = ex.getBindingResult().getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        return new JsonResult(400, errorInformation.toString(), null);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult<?> validationErrorHandler(ConstraintViolationException ex) {
        List<String> errorInformation = ex.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());
        return new JsonResult<>(400, errorInformation.toString(), null);
    }

    @ExceptionHandler(BindException.class)
    public JsonResult<?> validationErrorHandler(BindException ex) {
        List<String> errorInformation = ex.getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        return new JsonResult<>(400, errorInformation.toString(), null);
    }

}
